package com.heima.appgateway.filter;

import com.heima.appgateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;

// @Order(-1)
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.获取请求参数
        ServerHttpRequest request = exchange.getRequest();
        // 拿到请求路径
        String uri = request.getURI().getPath();
        if (uri.contains("/login")){
            // 登陆请求，放行
            return chain.filter(exchange);
        }

        //获取到放在请求头的token
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isEmpty(token)){
            // 5.否，拦截
            // 5.1.设置状态码
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            // 5.2.拦截请求
            return exchange.getResponse().setComplete();
        }

        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            int i = AppJwtUtil.verifyToken(claimsBody);
            if (i==1||i==2){
                // 5.否，拦截
                // 5.1.设置状态码
                exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
                // 5.2.拦截请求
                return exchange.getResponse().setComplete();
            }
        }catch (Exception e){
            // 5.否，拦截
            // 5.1.设置状态码
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            // 5.2.拦截请求
            return exchange.getResponse().setComplete();
        }

        // 登陆请求，放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
